﻿ 
// 创建人  ：LinJian
// 创建时间：2006-09-04
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.Security;
using Microsoft.Practices.EnterpriseLibrary.Data;
using WF_DataAccess;
using WF_Business;
using ChBusiness;

namespace ExtBusiness.Menu
{
    /// <!--
    /// 功能描述  : 菜单操作类
    /// 创建人  : LinJian
    /// 创建时间: 2006-09-04
    /// -->
    public class ClsMenuOperation : Page
    {
        private Database dbTemp = BasicOperate.CreateNetOfficeDataBase();

        /// <summary>
        /// 根据系统标识生成菜单
        /// </summary>
        /// <returns></returns>
        public  DataTable GenerateParentMenu(string userID)
        {
            string strSql = @"select a.* from sys_menu a join sys_usertype_menu_relation b on a.ID=b.Menu_ID ";
            strSql = strSql + "join sys_usertype c on c.id=b.usertype_id join sys_user d on d.Type=c.UserTypeCode ";
            strSql = strSql + "where a.parent_id is null and d.userID=:userID order by ORDER_FIELD asc";
            DbCommand cmd = dbTemp.GetSqlStringCommand(strSql);
            dbTemp.AddInParameter(cmd, "userID", DbType.String, userID);
            return dbTemp.ExecuteDataSet(cmd).Tables[0];
        }

        /// <summary>
        /// 根据系统标识父菜单ID生成菜单
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="strParentId">父菜单ID</param>
        /// <returns></returns>
        /// <!--
        /// 功能描述  : 菜单的生成与权限挂钩
        /// 修改人  : cd
        /// 修改时间: 2007-07-10
        /// -->
        public  DataTable GenerateChildMenu(string userID, string strParentId)
        {
            string strSql = @"select a.* from sys_menu a join sys_usertype_menu_relation b on a.ID=b.Menu_ID ";
            strSql = strSql + "join sys_usertype c on c.id=b.usertype_id join sys_user d on d.Type=c.UserTypeCode ";
            strSql = strSql + "where a.parent_id =:parentid and d.userID=:userID order by order_field";
            DbCommand cmd = dbTemp.GetSqlStringCommand(strSql);
            dbTemp.AddInParameter(cmd, "parentid", DbType.String, strParentId);
            dbTemp.AddInParameter(cmd, "userID", DbType.String, userID);
            return dbTemp.ExecuteDataSet(cmd).Tables[0];
        }


        /// 创建人  : Wu Hansi
        /// 创建时间: 2007-07-09
        /// 修改人  : Wu Hansi
        /// 修改时间: 2007-07-09
        /// 修改描述: 描述                 
        /// <summary>
        /// 得到排序好的所有菜单
        /// </summary>
        /// <returns></returns>
        public  DataTable GetMenusSorted()
        {
            string strSql = @"select t2.parent_id sortid,null parentMenu, t2.menu_title childMenu,t2.id, t2.menu_url, null child
                            from sys_menu t1, sys_menu t2 
                            where t1.ID = t2.parent_id UNION 
                            select t3.id sortid,menu_title parentMenu,null childMenu,id, menu_url,
                            (select count(*) from sys_menu t4 where t4.parent_id=t3.id) child
                            from sys_menu t3 
                            where t3.parent_id is null order by sortid desc,menu_url desc
                            ";
            return dbTemp.ExecuteDataSet(CommandType.Text, strSql).Tables[0];
        }

        /// <summary>
        /// 根据条件得到排序好的所有菜单
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public  DataTable GetMenusSorted(string str)
        {
            string strSql = @"select t2.parent_id sortid,null parentMenu, t2.menu_title childMenu,t2.id, t2.menu_url, null child
                            from sys_menu t1, sys_menu t2 
                            where t1.ID = t2.parent_id  and t2.menu_title like '%" +str + @"%' UNION 
                            select t3.id sortid,menu_title parentMenu,null childMenu,id, menu_url,
                            (select count(*) from sys_menu t4 where t4.parent_id=t3.id) child
                            from sys_menu t3 
                            where t3.parent_id is null and t3.menu_title like '%" + str + @"%' order by sortid desc,menu_url desc
                            ";
            return dbTemp.ExecuteDataSet(CommandType.Text, strSql).Tables[0];
        }
        /// <summary>
        /// 得到排序好的，带是否拥有权限的标志
        /// </summary>
        /// <param name="usertype_id"></param>
        /// <returns></returns>
        public  DataTable GetMenusSortedWithAuth(string usertype_id)
        {
            string strSql = @"select t2.parent_id sortid,null parentmenu, t2.menu_title childmenu,t2.id,t2.menu_url,
                            (select count(*) from sys_usertype_menu_relation s1 where 
                            s1.usertype_id='" + usertype_id + @"' and s1.menu_id=t2.id) auth
                            from sys_menu t1, sys_menu t2 where t1.ID = t2.parent_id
                            UNION 
                            select t3.id sortid,menu_title parentmenu,null childmenu,id,menu_url,
                            (select count(*) from sys_usertype_menu_relation s1 where 
                            s1.usertype_id='" + usertype_id + @"' and s1.menu_id=t3.id) auth
                            from sys_menu t3, sys_usertype_menu_relation s1
                            where t3.parent_id is null order by sortid desc, menu_url desc
                            ";
            return dbTemp.ExecuteDataSet(CommandType.Text, strSql).Tables[0];
        }

        /// <summary>
        /// 删除现有的菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public  bool DeleteMenu(string id)
        {
            string strSql = @"Delete from sys_menu where id = :row_id";

            DbCommand cmdTemp = dbTemp.GetSqlStringCommand(strSql);
            dbTemp.AddInParameter(cmdTemp, "row_id", DbType.String, id);
            return dbTemp.ExecuteNonQuery(cmdTemp) > 0 ? true : false;
        }

      
        /// <summary>
        /// 根据菜单id获取父菜单id
        /// </summary>
        /// <param name="strMenuId">菜单id</param>
        /// <returns></returns>
        public  string GetParentId(string strMenuId)
        {
            string strSql =string.Format(@"select PARENT_ID from SYS_MENU where id='{0}'",strMenuId);
            return dbTemp.ExecuteScalar(CommandType.Text, strSql).ToString();
        }

        /// <summary>
        /// Gets the child menus.
        /// </summary>
        /// <param name="strParentMenuName">Name of the STR parent menu.</param>
        /// <returns></returns>
        public DataTable GetChildMenus(string strParentMenuName)
        {
            string strSql = string.Format(@"select * from SYS_MENU where parent_id in 
                (select id from sys_menu where menu_title='{0}') order by order_field", strParentMenuName);
            return dbTemp.ExecuteDataSet(CommandType.Text, strSql).Tables[0];
        }

        /// <summary>
        /// 根据流程分类获得行政许可事项
        /// </summary>
        /// <param name="strFlowName">流程分类</param>
        /// <param name="strMenuTitle">标题</param>
        /// <returns></returns>
        public string GetFlow(string strMenuTitle, string strFlowName)
        {
            string strSql = string.Format(@"select {0} from xt_workflow_define where flowname='{1}'", strMenuTitle, strFlowName);
            return dbTemp.ExecuteScalar(CommandType.Text, strSql).ToString();
        }

        #region 迁移菜单操作方法
        /// <summary>
        /// 获取父菜单
        /// </summary>
        /// <returns></returns>
        public DataTable GetParentMenu()
        {
            string strSql = "select * from xt_menu_parent";

            Database dbTemp = BasicOperate.CreateNetOfficeDataBase();
            return dbTemp.ExecuteDataSet(CommandType.Text, strSql).Tables[0];
        }


       /// <summary>
        /// 添加子菜单
       /// </summary>
       /// <param name="parentmenu">父级菜单</param>
       /// <param name="menuname">当前菜单名</param>
       /// <param name="menuUrl">菜单链接地址</param>
       /// <param name="picture">图标地址</param>
        public void AddChildMenu(string parentmenu,string menuname,string menuUrl,string picture)
        {
            IDataAccess idaTemp = SysParams.OAConnection();
            string MaxParid = "select max(show_no)+1 from xt_menu_child where ancestor like '" + parentmenu + "'";
            DataTable dtMaxParId;
            idaTemp.RunSql(MaxParid, out dtMaxParId);
            string maxshowNo = "";
            if (dtMaxParId.Rows[0][0].ToString() != "")
                maxshowNo = dtMaxParId.Rows[0][0].ToString();
            else
                maxshowNo = "0";
            string insertmenu = "insert into xt_menu_child(menu_child_id,menu_child_desc,ancestor,linkhref,overpic,show_no) values(";
            insertmenu += "sys_guid(),'" + menuname + "','" + parentmenu + "','" + menuUrl + "','";
            insertmenu += picture + "','" + maxshowNo + "')";
            idaTemp.RunSql(insertmenu);

            string strId = "select menu_child_id from xt_menu_child where menu_child_desc like '" + menuname + "'";
            DataTable dtchildid;
            idaTemp.RunSql(strId, out dtchildid);

            //默认把管理员角色id（d33c0003-62c9-7399-7c70-b1b5ef62eb29）固定带入了
            string InsertMenuGroup = "insert into xt_group_menu(right_id,menu_child_id) values('d33c0003-62c9-7399-7c70-b1b5ef62eb29','" + dtchildid.Rows[0][0].ToString() + "')";
            idaTemp.RunSql(InsertMenuGroup);
        }
        /// <summary>
        /// 生成父菜单
        /// </summary>
        /// <returns></returns>
        public DataTable GenerateParentMenu()
        {
            string sqlmenuparent = "select * from xt_menu_parent";
            System.Data.DataTable dtparentmenu;
            SysParams.OAConnection().RunSql(sqlmenuparent, out dtparentmenu);
            return dtparentmenu;
        }
        /// <summary>
        /// 排序父菜单
        /// </summary>
        /// <returns></returns>
        public DataTable OrderParentMenu()
        {
            string strSqlmenuparent = "select * from xt_menu_parent order by show_no";
            DataTable dt;
            SysParams.OAConnection().RunSql(strSqlmenuparent, out dt);
            return dt;
        }
        /// <summary>
        /// 获取取子菜单
        /// </summary>
        /// <param name="menu_parent_id"></param>
        /// <returns></returns>
        public DataTable GetChildMenu(string menu_parent_id)
        {
            string strSqlmenuchild = "select * from xt_menu_child where ancestor like '" + menu_parent_id + "' order by show_no";
            DataTable dtchild;
            SysParams.OAConnection().RunSql(strSqlmenuchild, out dtchild);
            return dtchild;
        }
        
        /// <summary>
        /// 更新子菜单
        /// </summary>
        /// <param name="menuname">菜单名</param>
        /// <param name="parentmenu">父级菜单</param>
        /// <param name="menuUrl">菜单地址</param>
        /// <param name="picture">图片地址</param>
        /// <param name="childid"></param>
        /// <param name="strShowNo"></param>
        public void UpdateChildMenu(string menuname,string parentmenu,string menuUrl,string picture,string childid,string strShowNo)
        {
            string UpdateMenu = string.Format("update xt_menu_child set menu_child_desc='{0}',ancestor='{1}',linkhref='{2}',overpic='{3}',SHOW_NO='{4}'  where menu_child_id ='{5}'", menuname, parentmenu, menuUrl, picture, strShowNo,childid);
            SysParams.OAConnection().RunSql(UpdateMenu);
        }

        /// <summary>
        /// 删除子菜单
        /// </summary>
        /// <param name="delmenuchildid">菜单id</param>
        public void DeleteChildMenu(string delmenuchildid)
        {
            string delmenugroup = "delete from xt_group_menu where menu_child_id like '" + delmenuchildid + "'";
            SysParams.OAConnection().RunSql(delmenugroup);
            string delmenu = "delete from xt_menu_child where menu_child_id like '" + delmenuchildid + "'";
            SysParams.OAConnection().RunSql(delmenu);
        }

        /// <summary>
        /// 删除菜单组
        /// </summary>
        /// <param name="delmenuparentid">父级菜单id</param>
        public void DeleteMenuGroup(string delmenuparentid)
        {
            string delmenupar = "delete from xt_menu_parent where menu_parent_id like '" + delmenuparentid + "'";
            SysParams.OAConnection().RunSql(delmenupar);
        }

        /// <summary>
        /// 上移子菜单
        /// </summary>
        /// <param name="ChildMno">排序号</param>
        /// <param name="ChildMupParId">父级菜单id</param>
        /// <param name="ChildMupId">当前菜单id</param>
        public void MoveMenu(int ChildMno, string ChildMupParId, string ChildMupId)
        {
            int newId = ChildMno - 1;
            string UpshowNo = "update xt_menu_child set show_no=" + ChildMno + " where show_no=" + newId + " and ancestor like '" + ChildMupParId + "'";
            SysParams.OAConnection().RunSql(UpshowNo);

            string UpshowNoNew = "update xt_menu_child set show_no=" + newId + " where menu_child_id like '" + ChildMupId + "' and ancestor like '" + ChildMupParId + "'";
            SysParams.OAConnection().RunSql(UpshowNoNew);
        }

        /// <summary>
        /// 下移子菜单
        /// </summary>
        /// <param name="ChildMno">排序号</param>
        /// <param name="ChildMupParId">父级菜单id</param>
        /// <param name="ChildMupId">当前菜单id</param>
        public void MoveDownMenu(int ChildMdownno, string ChildMdownParId, string ChildMdownId)
        {
            int newId = ChildMdownno + 1;
            string UpshowNo = "update xt_menu_child set show_no=" + ChildMdownno + " where show_no=" + newId + " and ancestor like '" + ChildMdownParId + "'";
            int i = SysParams.OAConnection().RunSql(UpshowNo);
            string UpshowNoNew = "update xt_menu_child set show_no=" + newId + " where menu_child_id like '" + ChildMdownId + "' and ancestor like '" + ChildMdownParId + "'";
            int j = SysParams.OAConnection().RunSql(UpshowNoNew);
        }
        /// <summary>
        /// 上移菜单组
        /// </summary>
        /// <param name="ParUpNo"></param>
        /// <param name="ParUpId"></param>
        public void MoveUpMenuGroup(int ParUpNo, string ParUpId)
        {
            int NewNo = ParUpNo - 1;
            string UpparNo = "update xt_menu_parent set show_no=" + ParUpNo + " where show_no=" + NewNo;
            int i = SysParams.OAConnection().RunSql(UpparNo);
            string UpparNonew = "update xt_menu_parent set show_no=" + NewNo + " where menu_parent_id like '" + ParUpId + "'";
            int j = SysParams.OAConnection().RunSql(UpparNonew);
        }
        /// <summary>
        /// 下移菜单组
        /// </summary>
        /// <param name="ParDownNo"></param>
        /// <param name="ParDownId"></param>
        public void MoveDownMenuGroup(int ParDownNo, string ParDownId)
        {
            int NewNo = ParDownNo + 1;
            string UpparNo = "update xt_menu_parent set show_no=" + ParDownNo + " where show_no=" + NewNo;
            int i = SysParams.OAConnection().RunSql(UpparNo);
            string UpparNonew = "update xt_menu_parent set show_no=" + NewNo + " where menu_parent_id like '" + ParDownId + "'";
            int j = SysParams.OAConnection().RunSql(UpparNonew);
        }
        /// <summary>
        /// 插入子菜单
        /// </summary>
        public static void InserChildMenu(string menuname,string picpath)
        {
            string SelMaxNo = "select max(show_no)+1 from xt_menu_parent";
            DataTable dt;
            SysParams.OAConnection().RunSql(SelMaxNo, out dt);
            int showNo = Convert.ToInt32(dt.Rows[0][0]);
            string InsertParentM = "insert into xt_menu_parent(menu_parent_id,menu_parent_desc,show_no,picpath) values(sys_guid(),'" + menuname + "','" + showNo + "','"+picpath+"')";
            int i = SysParams.OAConnection().RunSql(InsertParentM);
        }
        /// <summary>
        /// 更新子菜单
        /// </summary>
        /// <param name="menuname"></param>
        /// <param name="parentid"></param>
        public static void UpdateChileMenu(string menuname,string parentid,string picpath)
        {
            string UpdateM = "update xt_menu_parent set menu_parent_desc='" + menuname + "',picpath='"+picpath+"' where menu_parent_id like '" + parentid + "'";
            int i = SysParams.OAConnection().RunSql(UpdateM);
        }
        /// <summary>
        /// 获取子菜单
        /// </summary>
        /// <param name="strParentDesc">父菜单的描述</param>
        /// <returns></returns>
        public DataTable GetChildMenuInfo(string strParentDesc)
        {
            string strSql = string.Format("select c.* from xt_menu_child c,xt_menu_parent p " +
                "where c.ancestor=p.menu_parent_id and p.MENU_PARENT_DESC='{0}' order by c.show_no",
                strParentDesc);

            Database dbTemp = BasicOperate.CreateNetOfficeDataBase();
            return dbTemp.ExecuteDataSet(CommandType.Text, strSql).Tables[0];
        }
        /// <summary>
        /// 保存菜单
        /// </summary>
        /// <param name="strGroupId"></param>
        public void SaveMenu(string strGroupId)
        {
            IDataAccess dataAccess = SysParams.OAConnection(true);

            try
            {
                String strSql = string.Format("delete from xt_group_menu where right_id='{0}'", strGroupId);
                dataAccess.RunSql(strSql);

                strSql = "select * from xt_menu_child";

                System.Data.DataTable dtOut;
                dataAccess.RunSql(strSql, out dtOut);

                foreach (System.Data.DataRow drRecord in dtOut.Rows)
                {
                    string strChildId = drRecord["MENU_CHILD_ID"].ToString();
                    string strChecked = Request[strChildId];

                    if (!string.IsNullOrEmpty(strChecked))
                    {
                        if (strChecked.Equals("checkbox"))
                        {
                            strSql = string.Format("insert into xt_group_menu(right_id,menu_child_id)" +
                                " values('{0}','{1}')", strGroupId, strChildId);
                            dataAccess.RunSql(strSql);
                        }
                    }
                }

                dataAccess.Close(true);
            }
            catch
            {
                dataAccess.Close(false);
                ClientScript.RegisterStartupScript(Page.GetType(), "returnHis", "window.location.href='manage_group_menu.aspx'");
            }	
        }

        /// <summary>
        /// 获取子菜单的个数
        /// </summary>
        /// <param name="strParentDesc">父菜单的描述</param>
        /// <returns></returns>
        public string GetChildMenuCount(string strParentDesc)
        {
            string strSql = string.Format("select count(c.menu_child_id) as countchild from xt_menu_child c,"
                + "xt_menu_parent p where c.ancestor=p.menu_parent_id and p.MENU_PARENT_DESC='{0}'",
                strParentDesc);

            string strCount = SysParams.OAConnection().GetValue(strSql);
            return strCount;
        }

        /// <summary>
        /// 判断子菜单是否选中
        /// </summary>
        /// <param name="strRightId"></param>
        /// <param name="strMenuChildId"></param>
        /// <returns></returns>
        public string GetCheckedMenuId(string strRightId, string strMenuChildId)
        {
            string strSql = string.Format("select menu_child_id from xt_group_menu where right_id='{0}'" +
                " and menu_child_id='{1}'", strRightId, strMenuChildId);

            Database dbTemp = BasicOperate.CreateNetOfficeDataBase();
            object objReturn = dbTemp.ExecuteScalar(CommandType.Text, strSql);
            if (objReturn != null)
            {
                return objReturn.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion
    }
}
